package com.wavecoler.professor.dao;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import com.wavecoler.dao.PMF;
import com.wavecoler.professor.objects.Session;
import java.util.*;
import java.util.logging.Logger;
import javax.jdo.Query;

public class SessionDAO {

	private static final Logger log = Logger
			.getLogger(SessionDAO.class.getName());

	// Method to insert a new group
	public static void insertSession(Session session) {
		PersistenceManager pm = null;

		// LLamamos a la clase que tendra la persistencia
		pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(session);
			tx.commit();
		} catch (Exception e) {
			log.warning(e.getMessage());
			log.info(e.getMessage());
			e.printStackTrace();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
				log.warning("did transaction rollback");
			}
			if (pm != null)
				pm.close();
		}
	}

	// Method to get a list of groups
	public static List<Session> getSessionsByParticipant(String type, String ID) {
		PersistenceManager pm = null;
		try {
			// LLamamos a la clase que tendra la persistencia
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("select from " + Session.class.getName()
					+ " where sessionType == :p1 AND participant == :p2");
			List<Session> sessions = (List<Session>) query.execute(type, ID);
			sessions.size();
			return sessions;
		} catch (Exception e) {
			log.warning(e.getMessage());
			log.info(e.getMessage());
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	// Method to return the list of groups
	public static List<Session> getSessionList() {
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("select from " + Session.class.getName()
					+ "");
			List<Session> session = (List<Session>) query.execute();
			session.size();
			return session;
		} catch (Exception e) {
			log.info(e.getMessage());
			log.warning(e.getMessage());
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

}